import { computed } from 'vue'
import Taro from '@tarojs/taro'
import { useMedicalRecordStore } from '@/store/modules'

export interface ItemWithImages {
  title?: string
  description: string
  images: string[]
}

export interface DiagnosisItem {
  diseaseName: string
  occupation?: string | number  // 职业
  diagnosisResult: string
  diagnosisResultImages: string[]
  diagnosisBasis: string
  diagnosisBasisImages: string[]
}

export interface MedicationRecord {
  drugName: string
  medicationMethod: string
  dosage: string
  medicationFrequency: string
  medicationTime: string
  effect: string
}

export function useItemManagement() {
  const medicalRecordStore = useMedicalRecordStore()
  
  const formData = computed(() => {
    const storeData = medicalRecordStore.getData
    if (storeData) {
      return storeData
    }
    // 如果 store 中没有数据，初始化默认数据
    const defaultData = medicalRecordStore.getDefaultFormData()
    medicalRecordStore.initializeFormData(defaultData)
    return defaultData
  })

  const updateField = (field: string, value: any) => {
    console.log("更新字段:", field, value)
    medicalRecordStore.updateField(field as any, value)
  }

  // 通用项目管理函数
  const updateItem = (arrayField: string, index: number, field: string, value: any) => {
    console.log("更新项目:", arrayField, index, field, value)
    
    if (!formData.value[arrayField]) {
      updateField(arrayField, [])
    }
    
    const updatedItems = [...formData.value[arrayField]]
    updatedItems[index] = {
      ...updatedItems[index],
      [field]: value
    }
    
    updateField(arrayField, updatedItems)
  }

  const addItem = (arrayField: string, newItem: any, successMessage: string) => {
    console.log("添加项目:", arrayField)
    console.log("formData.value:", formData.value)
    console.log("formData.value[arrayField]:", formData.value[arrayField])
    
    if (!formData.value[arrayField]) {
      console.log("数组不存在，初始化为空数组")
      updateField(arrayField, [])
    }
    
    const currentItems = formData.value[arrayField] || []
    console.log("当前项目:", currentItems)
    const updatedItems = [...currentItems, newItem]
    console.log("更新后的项目:", updatedItems)
    updateField(arrayField, updatedItems)
    
    console.log("更新后的 formData.value[arrayField]:", formData.value[arrayField])
    
    Taro.showToast({
      title: successMessage,
      icon: 'none',
      duration: 1500
    })
  }

  const removeItem = (arrayField: string, index: number, minCount: number = 1, errorMessage: string, successMessage: string) => {
    console.log("删除项目:", arrayField, index)
    
    if (formData.value[arrayField] && formData.value[arrayField].length <= minCount) {
      Taro.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 1500
      })
      return
    }
    
    const updatedItems = formData.value[arrayField].filter((_: any, i: number) => i !== index)
    updateField(arrayField, updatedItems)
    
    Taro.showToast({
      title: successMessage,
      icon: 'success',
      duration: 1500
    })
  }

  // 诊断项目管理
  const updateDiagnosisItem = (index: number, field: string, value: any) => {
    updateItem('diagnosisItems', index, field, value)
  }

  const addDiagnosisItem = () => {
    const newItem: DiagnosisItem = {
      diseaseName: "",
      occupation: 2,  // 默认值：专业技术人员（护士职业通常属于此类别）
      diagnosisResult: "",
      diagnosisResultImages: [],
      diagnosisBasis: "",
      diagnosisBasisImages: []
    }
    addItem('diagnosisItems', newItem, '添加诊断项目成功')
  }

  const removeDiagnosisItem = (index: number) => {
    removeItem('diagnosisItems', index, 1, '至少需要保留一个诊断项目', '删除诊断项目成功')
  }

  // 处置项目管理
  const updateDispositionItem = (index: number, data: ItemWithImages) => {
    if (!formData.value.dispositionItems) {
      updateField('dispositionItems', [])
      return
    }
    
    const updatedItems = [...formData.value.dispositionItems]
    updatedItems[index] = {
      title: data.title || "",
      description: data.description || "",
      images: data.images || []
    }
    updateField('dispositionItems', updatedItems)
  }

  const addDispositionItem = () => {
    const newItem: ItemWithImages = {
      title: "",
      description: "",
      images: []
    }
    addItem('dispositionItems', newItem, '添加处置项目成功')
  }

  const removeDispositionItem = (index: number) => {
    removeItem('dispositionItems', index, 0, '', '删除处置项目成功')
  }

  // 健康教育项目管理
  const updateHealthEducationItem = (index: number, data: ItemWithImages) => {
    if (!formData.value.healthEducationItems) {
      updateField('healthEducationItems', [])
      return
    }
    
    const updatedItems = [...formData.value.healthEducationItems]
    updatedItems[index] = {
      title: data.title || "",
      description: data.description || "",
      images: data.images || []
    }
    updateField('healthEducationItems', updatedItems)
  }

  const addHealthEducationItem = () => {
    const newItem: ItemWithImages = {
      title: "",
      description: "",
      images: []
    }
    addItem('healthEducationItems', newItem, '添加健康教育项目成功')
  }

  const removeHealthEducationItem = (index: number) => {
    removeItem('healthEducationItems', index, 0, '', '删除健康教育项目成功')
  }

  // 手术项目管理
  const updateSurgeryItem = (index: number, data: ItemWithImages) => {
    if (!formData.value.surgeryItems) {
      updateField('surgeryItems', [])
      return
    }
    
    const updatedItems = [...formData.value.surgeryItems]
    updatedItems[index] = {
      title: data.title || "",
      description: data.description || "",
      images: data.images || []
    }
    updateField('surgeryItems', updatedItems)
  }

  const addSurgeryItem = () => {
    const newItem: ItemWithImages = {
      title: "",
      description: "",
      images: []
    }
    addItem('surgeryItems', newItem, '添加手术史项目成功')
  }

  const removeSurgeryItem = (index: number) => {
    removeItem('surgeryItems', index, 0, '', '删除手术史项目成功')
  }

  // 过敏项目管理
  const updateAllergyItem = (index: number, data: ItemWithImages) => {
    if (!formData.value.allergyItems) {
      updateField('allergyItems', [])
      return
    }
    
    const updatedItems = [...formData.value.allergyItems]
    updatedItems[index] = {
      title: data.title || "",
      description: data.description || "",
      images: data.images || []
    }
    updateField('allergyItems', updatedItems)
  }

  const addAllergyItem = () => {
    const newItem: ItemWithImages = {
      title: "",
      description: "",
      images: []
    }
    addItem('allergyItems', newItem, '添加过敏史项目成功')
  }

  const removeAllergyItem = (index: number) => {
    removeItem('allergyItems', index, 0, '', '删除过敏史项目成功')
  }

  // 接种项目管理
  const updateVaccinationItem = (index: number, data: ItemWithImages) => {
    if (!formData.value.vaccinationItems) {
      updateField('vaccinationItems', [])
      return
    }
    
    const updatedItems = [...formData.value.vaccinationItems]
    updatedItems[index] = {
      title: data.title || "",
      description: data.description || "",
      images: data.images || []
    }
    updateField('vaccinationItems', updatedItems)
  }

  const addVaccinationItem = () => {
    const newItem: ItemWithImages = {
      title: "",
      description: "",
      images: []
    }
    addItem('vaccinationItems', newItem, '添加接种项目成功')
  }

  const removeVaccinationItem = (index: number) => {
    removeItem('vaccinationItems', index, 0, '', '删除接种项目成功')
  }

  // 筛查项目管理
  const updateScreeningItem = (index: number, data: ItemWithImages) => {
    if (!formData.value.screeningItems) {
      updateField('screeningItems', [])
      return
    }
    
    const updatedItems = [...formData.value.screeningItems]
    updatedItems[index] = {
      title: data.title || "",
      description: data.description || "",
      images: data.images || []
    }
    updateField('screeningItems', updatedItems)
  }

  const addScreeningItem = () => {
    const newItem: ItemWithImages = {
      title: "",
      description: "",
      images: []
    }
    addItem('screeningItems', newItem, '添加筛查项目成功')
  }

  const removeScreeningItem = (index: number) => {
    removeItem('screeningItems', index, 0, '', '删除筛查项目成功')
  }

  // 周期性健康检查项目管理
  const updatePeriodicHealthCheckItem = (index: number, data: ItemWithImages) => {
    if (!formData.value.periodicHealthCheckItems) {
      updateField('periodicHealthCheckItems', [])
      return
    }
    
    const updatedItems = [...formData.value.periodicHealthCheckItems]
    updatedItems[index] = {
      title: data.title || "",
      description: data.description || "",
      images: data.images || []
    }
    updateField('periodicHealthCheckItems', updatedItems)
  }

  const addPeriodicHealthCheckItem = () => {
    const newItem: ItemWithImages = {
      title: "",
      description: "",
      images: []
    }
    addItem('periodicHealthCheckItems', newItem, '添加周期性健康检查项目成功')
  }

  const removePeriodicHealthCheckItem = (index: number) => {
    removeItem('periodicHealthCheckItems', index, 0, '', '删除周期性健康检查项目成功')
  }

  // 生活方式项目管理
  const updateLifestyleItem = (index: number, data: ItemWithImages) => {
    if (!formData.value.lifestyleItems) {
      updateField('lifestyleItems', [])
      return
    }
    
    const updatedItems = [...formData.value.lifestyleItems]
    updatedItems[index] = {
      title: data.title || "",
      description: data.description || "",
      images: data.images || []
    }
    updateField('lifestyleItems', updatedItems)
  }

  const addLifestyleItem = () => {
    const newItem: ItemWithImages = {
      title: "",
      description: "",
      images: []
    }
    addItem('lifestyleItems', newItem, '添加生活方式项目成功')
  }

  const removeLifestyleItem = (index: number) => {
    removeItem('lifestyleItems', index, 0, '', '删除生活方式项目成功')
  }

  // 收案项目管理
  const updateAdmissionItem = (index: number, data: ItemWithImages) => {
    if (!formData.value.admissionItems) {
      updateField('admissionItems', [])
      return
    }
    
    const updatedItems = [...formData.value.admissionItems]
    updatedItems[index] = {
      title: data.title || "",
      description: data.description || "",
      images: data.images || []
    }
    updateField('admissionItems', updatedItems)
  }

  const addAdmissionItem = () => {
    const newItem: ItemWithImages = {
      title: "",
      description: "",
      images: []
    }
    addItem('admissionItems', newItem, '添加收案项目成功')
  }

  const removeAdmissionItem = (index: number) => {
    removeItem('admissionItems', index, 0, '', '删除收案项目成功')
  }

  // 居家护理记录管理
  const updateHomeCareRecord = (index: number, data: ItemWithImages) => {
    if (!formData.value.homeCareRecords) {
      updateField('homeCareRecords', [])
      return
    }
    
    const updatedItems = [...formData.value.homeCareRecords]
    updatedItems[index] = {
      title: data.title || "",
      description: data.description || "",
      images: data.images || []
    }
    updateField('homeCareRecords', updatedItems)
  }

  const addHomeCareRecord = () => {
    console.log("addHomeCareRecord 被调用")
    console.log("当前 formData.homeCareRecords:", formData.value.homeCareRecords)
    
    const newItem: ItemWithImages = {
      title: "",
      description: "",
      images: []
    }
    console.log("新项目:", newItem)
    addItem('homeCareRecords', newItem, '添加护理记录成功')
    
    console.log("添加后的 formData.homeCareRecords:", formData.value.homeCareRecords)
  }

  const removeHomeCareRecord = (index: number) => {
    removeItem('homeCareRecords', index, 0, '', '删除护理记录成功')
  }

  // 监护人评价管理
  const updateGuardianEvaluation = (index: number, data: any) => {
    if (!formData.value.guardianEvaluations) {
      updateField('guardianEvaluations', [])
      return
    }
    
    const updatedItems = [...formData.value.guardianEvaluations]
    updatedItems[index] = {
      ...updatedItems[index],
      ...data
    }
    updateField('guardianEvaluations', updatedItems)
  }

  const addGuardianEvaluation = () => {
    const newItem = {
      content: "",
      satisfaction: 0,
      details: {
        title: "",
        description: "",
        images: []
      }
    }
    addItem('guardianEvaluations', newItem, '添加监护人评价成功')
  }

  const removeGuardianEvaluation = (index: number) => {
    removeItem('guardianEvaluations', index, 0, '', '删除监护人评价成功')
  }

  const updateGuardianEvaluationSatisfaction = (index: number, satisfaction: number) => {
    if (!formData.value.guardianEvaluations) {
      updateField('guardianEvaluations', [])
      return
    }
    
    const updatedItems = [...formData.value.guardianEvaluations]
    updatedItems[index] = {
      ...updatedItems[index],
      satisfaction: satisfaction
    }
    updateField('guardianEvaluations', updatedItems)
  }

  const updateGuardianEvaluationDetails = (index: number, details: any) => {
    if (!formData.value.guardianEvaluations) {
      updateField('guardianEvaluations', [])
      return
    }
    
    const updatedItems = [...formData.value.guardianEvaluations]
    updatedItems[index] = {
      ...updatedItems[index],
      details: details
    }
    updateField('guardianEvaluations', updatedItems)
  }

  // 服务人员评价管理
  const updateStaffEvaluation = (index: number, data: ItemWithImages) => {
    if (!formData.value.staffEvaluations) {
      updateField('staffEvaluations', [])
      return
    }
    
    const updatedItems = [...formData.value.staffEvaluations]
    updatedItems[index] = {
      title: data.title || "",
      description: data.description || "",
      images: data.images || []
    }
    updateField('staffEvaluations', updatedItems)
  }

  const addStaffEvaluation = () => {
    const newItem: ItemWithImages = {
      title: "",
      description: "",
      images: []
    }
    addItem('staffEvaluations', newItem, '添加服务人员评价成功')
  }

  const removeStaffEvaluation = (index: number) => {
    removeItem('staffEvaluations', index, 0, '', '删除服务人员评价成功')
  }

  // 服务机构评价管理
  const updateInstitutionEvaluation = (index: number, data: ItemWithImages) => {
    if (!formData.value.institutionEvaluations) {
      updateField('institutionEvaluations', [])
      return
    }
    
    const updatedItems = [...formData.value.institutionEvaluations]
    updatedItems[index] = {
      title: data.title || "",
      description: data.description || "",
      images: data.images || []
    }
    updateField('institutionEvaluations', updatedItems)
  }

  const addInstitutionEvaluation = () => {
    const newItem: ItemWithImages = {
      title: "",
      description: "",
      images: []
    }
    addItem('institutionEvaluations', newItem, '添加服务机构评价成功')
  }

  const removeInstitutionEvaluation = (index: number) => {
    removeItem('institutionEvaluations', index, 0, '', '删除服务机构评价成功')
  }

  // 反馈项目管理
  const updateFeedbackItem = (index: number, data: ItemWithImages) => {
    if (!formData.value.feedbackItems) {
      updateField('feedbackItems', [])
      return
    }
    
    const updatedItems = [...formData.value.feedbackItems]
    updatedItems[index] = {
      title: data.title || "",
      description: data.description || "",
      images: data.images || []
    }
    updateField('feedbackItems', updatedItems)
  }

  const addFeedbackItem = () => {
    const newItem: ItemWithImages = {
      title: "",
      description: "",
      images: []
    }
    addItem('feedbackItems', newItem, '添加反馈项目成功')
  }

  const removeFeedbackItem = (index: number) => {
    removeItem('feedbackItems', index, 0, '', '删除反馈项目成功')
  }

  // 用药记录管理
  const addMedicationRecord = () => {
    const newItem: MedicationRecord = {
      drugName: '',
      medicationMethod: '',
      dosage: '',
      medicationFrequency: '',
      medicationTime: '',
      effect: ''
    }
    addItem('medicationRecords', newItem, '添加用药记录成功')
  }

  const removeMedicationRecord = (index: number) => {
    Taro.showModal({
      title: '确认删除',
      content: '确定要删除这条用药记录吗？',
      success: (res) => {
        if (res.confirm) {
          const currentRecords = formData.value.medicationRecords || []
          const updatedRecords = currentRecords.filter((_, i) => i !== index)
          updateField('medicationRecords', updatedRecords)
          
          Taro.showToast({
            title: '删除成功',
            icon: 'success',
            duration: 1500
          })
        }
      }
    })
  }

  return {
    formData,
    updateField,
    updateDiagnosisItem,
    addDiagnosisItem,
    removeDiagnosisItem,
    updateDispositionItem,
    addDispositionItem,
    removeDispositionItem,
    updateHealthEducationItem,
    addHealthEducationItem,
    removeHealthEducationItem,
    updateSurgeryItem,
    addSurgeryItem,
    removeSurgeryItem,
    updateAllergyItem,
    addAllergyItem,
    removeAllergyItem,
    updateVaccinationItem,
    addVaccinationItem,
    removeVaccinationItem,
    updateScreeningItem,
    addScreeningItem,
    removeScreeningItem,
    updatePeriodicHealthCheckItem,
    addPeriodicHealthCheckItem,
    removePeriodicHealthCheckItem,
    updateLifestyleItem,
    addLifestyleItem,
    removeLifestyleItem,
    updateAdmissionItem,
    addAdmissionItem,
    removeAdmissionItem,
    updateHomeCareRecord,
    addHomeCareRecord,
    removeHomeCareRecord,
    updateGuardianEvaluation,
    addGuardianEvaluation,
    removeGuardianEvaluation,
    updateGuardianEvaluationSatisfaction,
    updateGuardianEvaluationDetails,
    updateStaffEvaluation,
    addStaffEvaluation,
    removeStaffEvaluation,
    updateInstitutionEvaluation,
    addInstitutionEvaluation,
    removeInstitutionEvaluation,
    updateFeedbackItem,
    addFeedbackItem,
    removeFeedbackItem,
    addMedicationRecord,
    removeMedicationRecord
  }
}
